package com.glorious.gcontacts.spring.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glorious.gcontacts.model.GoogleContactInfo;
import com.glorious.gcontacts.model.UserData;
import com.glorious.gcontacts.spring.repositories.UserDataDTO;
import com.google.appengine.api.users.User;

@Service
public class UsersService
{
	private CacheService cacheService;
	private UserDataDTO userDataDTO;
	
	@Autowired
	public void setCacheService(CacheService cacheService)
	{
		this.cacheService = cacheService;
	}

	@Autowired
	public void setUserDataDTO(UserDataDTO userDataDTO)
	{
		this.userDataDTO = userDataDTO;
	}

	public void updateUserData(UserData data)
	{
		cacheService.setUserData(data);
		userDataDTO.saveUserData(data);
	}
	
	public UserData getUserData(User user)
	{
		UserData data = null;
		//first, look in cache for userData
		if(cacheService.isUserDataCached(user))
		{
			data = cacheService.getUserData(user);
		}
		else
		{
			//if not in cache, retrieve from datastore
			data = userDataDTO.getUserData(user);
			if(data == null)
			{
				//if not in cache neither datastore, create a new one, persit it and cache it
				data = new UserData();
				data.setUser(user);
				data.setGoogleContactInfo(new GoogleContactInfo());
				userDataDTO.saveUserData(data);
			}
			/*else
			{
				//update User
				data.setUser(user);
				userDataDTO.saveUserData(data);
			}*/
			cacheService.setUserData(data);
		}		
		return data;
	}
}
